import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import {statusCode} from '@/utils/index'

axios.defaults.withcredentials = true;

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['user_token'] = getToken();
    }
    return config;
  },
  error => {
    console.log(error)
    return Promise.reject(error);
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data;
    if(res.code === statusCode.success || res.code === 20020){
      return res;
    }else{
      if(response.request.responseURL.split('/').slice(-1)[0] === 'login'){
        Message({
          message: res.message,
          type: 'error',
          duration: 3 * 1000
        }).then(()=>{
          store.dispatch('user/resetToken').then(()=>{
            location.reload()  // 为了重新实例化vue-router对象 避免bug
          })
        })
      }else if(res.code !== statusCode.not_login){
        Message({
          message: res.message || '请求接口有误，请联系技术人员',
          type: 'error',
          duration: 5 * 1000
        }).then(()=>{
          store.dispatch('user/resetToken').then(()=>{
            location.reload()  // 为了重新实例化vue-router对象 避免bug
          })
        })
      }

      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            store.dispatch('user/resetToken').then(() => {
            location.reload()  // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 6 * 10000
    })
    return Promise.reject(error)
  }
)

export default service
